package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.article.config.ApArticleThreadLocalUtil;
import com.heima.article.service.IApCollectionBehaviorService;
import com.heima.common.constants.BehaviorContstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
@Transactional
public class ApCollectionBehaviorServiceImpl implements IApCollectionBehaviorService {

    @Resource
    private CacheService cacheService;

    /**
     * 文章收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //判断是否登录
        ApUser user = ApArticleThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断是否收藏
        String collectionJson =
                (String) cacheService.hGet(BehaviorContstants.COLLECTION_BEHAVIOR + user.getId().toString(), String.valueOf(dto.getEntryId()));
        if (StringUtils.isNotBlank(collectionJson) && dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
        }


        if (dto.getOperation() == 0) {
            //收藏
            log.info("用户{}收藏文章{}，{}", user.getId(), dto.getEntryId(), JSON.toJSONString(dto));
            cacheService.hPut(BehaviorContstants.COLLECTION_BEHAVIOR + user.getId().toString(), String.valueOf(dto.getEntryId()), JSON.toJSONString(dto));
        } else {
            //取消收藏
            log.info("用户{}取消收藏文章{}，{}", user.getId(), dto.getEntryId(), JSON.toJSONString(dto));
            cacheService.hDelete(BehaviorContstants.COLLECTION_BEHAVIOR + user.getId().toString(), String.valueOf(dto.getEntryId()));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
